#include "Sphere.h"

namespace RayTracer
{
	bool Sphere::Hit(const Ray& r, float t_min, float t_max, HitRecord& rec) const {
		vec3 oc = r.origin() - center;
		auto a = glm::dot(r.direction(), r.direction());
		auto half_b = dot(oc, r.direction());
		auto c = glm::dot(oc, oc) - radius * radius;

		auto discriminant = half_b * half_b - a * c;
		if (discriminant < 0) return false;
		auto sqrtd = sqrt(discriminant);


		auto root = (-half_b - sqrtd) / a;
		if (root < t_min || t_max < root) {
			root = (-half_b + sqrtd) / a;
			if (root < t_min || t_max < root)
				return false;
		}

		rec.t = root;
		rec.position = r.at(rec.t);
		vec3 outward_normal = (rec.position - center) / radius;
		rec.set_face_normal(r, outward_normal);
		GetSphereUV(outward_normal, rec.u, rec.v);
		rec.matPtr = matPtr;
		return true;
	}

	bool Sphere::BoundingBox(AABB & output_box) const
	{
		output_box = AABB(
			center - vec3(radius, radius, radius),
			center + vec3(radius, radius, radius));
		return true;
	}
}